import { createContext, useState, useContext, PropsWithChildren, useEffect } from 'react';

type PathItem = {
  href?: string,
  title: string
}
type CurrentHeaderContextType = {
  currentPath: PathItem[];
  setCurrentPath: (path: PathItem[]) => void;
};
const CurrentHeaderContext = createContext<CurrentHeaderContextType | undefined>(undefined);
export const useCurrentHeader = () => {
  const context = useContext(CurrentHeaderContext);
  if (!context) {
    throw new Error('useCurrentHeader must be used within a CurrentHeaderProvider');
  }
  return context;
};
export const usePath = (items: PathItem[]) => {
  const { setCurrentPath } = useCurrentHeader();
  const json = JSON.stringify(items);
  useEffect(() => {
    setCurrentPath(items);
  }, [json])
}

export const CurrentHeaderProvider = ({ children }: PropsWithChildren) => {
  const [currentPath, setCurrentPath] = useState<PathItem[]>([]); // 默认路径为首页
  return (
    <CurrentHeaderContext.Provider value={{ currentPath, setCurrentPath }}>
      {children}
    </CurrentHeaderContext.Provider>
  );
};